package com.lenovo.smarttraffic.Runable;

import android.util.Log;

import com.google.gson.Gson;
import com.lenovo.smarttraffic.api.VolleyCallBack;
import com.lenovo.smarttraffic.bean.EnvironmentBean;
import com.lenovo.smarttraffic.bean.GsonBean.SenseBean;
import com.lenovo.smarttraffic.util.CommonUtil;
import com.lenovo.smarttraffic.util.VolleyUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;

import java.util.Date;
import java.util.List;

/**
 * on 2020-07-17
 * at 15:40
 *
 * @author Caleb.F
 * @Description
 */
public class  GetDataRunbale implements Runnable {
    private static final String TAG = "MyInvironmentCallable";

    @Override
    public void run() {
        VolleyUtil.post("GetAllSense.do", new JSONObject(), new VolleyCallBack() {
            @Override
            public void onSucceess(JSONObject jsonObject, String response) {
                Log.d(TAG, "onSucceess: =====getSandBoxData");
                SenseBean senseBean = new Gson().fromJson(response, SenseBean.class);
                getRoadStatus(senseBean);
            }

            @Override
            public void onFailure(String onError) {
                Log.d(TAG, "onFailure: ---------------");
            }
        });
    }

    /**
     * 获取道路状态
     *
     * @param senseBean
     */
    private void getRoadStatus(SenseBean senseBean) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("RoadId", 1);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        VolleyUtil.post("GetRoadStatus.do", jsonObject, new VolleyCallBack() {
            @Override
            public void onSucceess(JSONObject jsonObject, String response) {
                if (jsonObject.optString("RESULT").equals("S")) {
                    int status = jsonObject.optInt("Status");
                    EnvironmentBean environmentBean = new EnvironmentBean(
                            senseBean.getTemperature(), senseBean.getHumidity(),
                            senseBean.get_$Pm25270(), senseBean.getCo2(), senseBean.getLightIntensity()
                            , status, CommonUtil.getSimpleDateFormat().format(new Date()));
                    environmentBean.save();
                    List<EnvironmentBean> all = LitePal.findAll(EnvironmentBean.class);
                    int size = all.size();
                    if (size == 21) {
                        EnvironmentBean first = LitePal.findFirst(EnvironmentBean.class);
                        first.delete();
                    } else if (size > 21) {
                        LitePal.deleteAll(EnvironmentBean.class);
                    }

                }

            }

            @Override
            public void onFailure(String onError) {

            }
        });
    }
}
